package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.service.*;
import com.itheima.reggie.vo.StaticsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/statics")
public class StaticsController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private CategoryService categoryService;  //菜品分类
    @Autowired
    private DishService dishService;  //菜品
    @Autowired
    private OrderDetailService orderDetailService;  //订单明细
    @Autowired
    private SetmealService setmealService;


    @Autowired
    private OrderDetailMapper orderDetailMapper;

    //接口一：菜系营收占比分析  请求url地址：/statics/dishCash
    @GetMapping("/dishCash")
    public StaticsVO dishValueCash() {
        log.info("[接口一：菜系营收占比分析]:------------------");
        ///1。查询数据库【菜系营收占】  map[NAME,VALUE]
        List<Map<String, Object>> dishValueCash = orderDetailMapper.dishValueCash();
        log.info("[]:dishValueCash={}",dishValueCash);

        StaticsVO staticsVO=new StaticsVO();
        List<Map> list=dishValueCash.stream().map(item->{
            Map resultMap = new HashMap();
            resultMap.put("value",item.get("VALUE"));
            resultMap.put("name",item.get("NAME"));
            return resultMap;
        }).collect(Collectors.toList());

        staticsVO.setDishCategoryCash(list);
        return staticsVO;
    }

    //接口二：套餐营收占比分析  请求url地址：/statics/setmealCash
    @GetMapping("/setmealCash")
    public StaticsVO setmealValueCash() {
        log.info("[接口二：套餐营收占比分析]:------------------");
        ///1。查询数据库【套餐营收占】  map[NAME,VALUE]
        List<Map<String, Object>> dishValueCash = orderDetailMapper.setmealValueCash();
        log.info("[]:dishValueCash={}",dishValueCash);

        StaticsVO staticsVO=new StaticsVO();
        List<Map> list=dishValueCash.stream().map(item->{
            Map resultMap = new HashMap();
            resultMap.put("value",item.get("VALUE"));
            resultMap.put("name",item.get("NAME"));
            return resultMap;
        }).collect(Collectors.toList());

        staticsVO.setSetmealCash(list);
        return staticsVO;
    }

    //接口三：菜系销量占比分析  请求url地址：/statics/dishNum
    @GetMapping("/dishNum")
    public StaticsVO dishNum() {
        log.info("[接口三：菜系销量占比分析]:------------------");
        ///1。查询数据库【菜系营收占】  map[NAME,VALUE]
        List<Map<String, Object>> dishValueCash = orderDetailMapper.dishNum();
        log.info("[]:dishValueCash={}",dishValueCash);

        StaticsVO staticsVO=new StaticsVO();
        List<Map> list=dishValueCash.stream().map(item->{
            Map resultMap = new HashMap();
            resultMap.put("value",item.get("VALUE"));
            resultMap.put("name",item.get("NAME"));
            return resultMap;
        }).collect(Collectors.toList());

        staticsVO.setDishNum(list);
        return staticsVO;
    }
    //接口四：套餐销量占比分析 请求url地址：/statics/dishNum
    @GetMapping("/setmealNum")
    public StaticsVO setmealNum() {
        log.info("[接口四：套餐销量占比分析]:------------------");
        ///1。查询数据库【菜系营收占】  map[NAME,VALUE]
        List<Map<String, Object>> dishValueCash = orderDetailMapper.setmealNum();
        log.info("[]:dishValueCash={}",dishValueCash);

        StaticsVO staticsVO=new StaticsVO();
        List<Map> list=dishValueCash.stream().map(item->{
            Map resultMap = new HashMap();
            resultMap.put("value",item.get("VALUE"));
            resultMap.put("name",item.get("NAME"));
            return resultMap;
        }).collect(Collectors.toList());

        staticsVO.setSetmealNum(list);
        return staticsVO;
    }


    //接口五：月营业额趋势图  请求url地址：/statics/cashPerMonth
    @GetMapping("/cashPerMonth")
    public Map cashPerMonth() throws ParseException {
        log.info("[接口五：月营业额趋势图]:------------------");
        ///1。查询数据库【每月售数据】  map[monthList,dataList]
        List<Map<String, Object>> cashPerMonth = orderDetailMapper.cashPerMonth(2023);

        //2。--查询的【时间范围】
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM");
        LocalDate nowDate = LocalDate.now();   //当前时间：2023-03-22
        LocalDate beforeDate = LocalDate.now().minusYears(1);  //去年时间：2022-03-22

        //3，创建集合
        List<String> timeList = new ArrayList<>();//创建空集合，封装每月表
        List<Integer> dataList = new ArrayList<>();//创建空集合，封装每月销售额

        //4，遍历十二个月，查询当前月是否有销售额，如果有将销售额存储到集合中，如果没有，将0存储到集合中
        //2022-03 ，2022-04，2022-05，......，2023-03   nowDate.plusMonths(1)=2023-04-22
        while (beforeDate.isBefore(nowDate.plusMonths(1))) {
            //每月表集合--添加
            String time = beforeDate.format(fmt);
            timeList.add(time);
            //查询指定月是否存在销售额
            Optional<Map<String, Object>> optional = cashPerMonth.stream()
                    .filter(item -> item.get("monthList").equals(time)).findFirst();
            if (optional.isPresent()) {
                //存在销售额，将销售额存储到 售额集合中
                BigDecimal dataList1 = (BigDecimal) optional.get().get("monthValueList");
                dataList.add(dataList1.intValue());
            } else {
                ///不存在销售额，将销售额0存储到 售额集合中
                dataList.add(0);
            }
            beforeDate = beforeDate.plusMonths(1);
        }
        //5。封装查询结果数据
        Map resultMap = new HashMap();
        resultMap.put("monthList",timeList);  //每月时间列表
        resultMap.put("monthValueList",dataList); // 每月销售额列表
        return resultMap;
    }












    //参考-----------------------------------------
    public Map cashPerMonth_Bdsafjafvkafkv() throws ParseException {
        log.info("[接口五：月营业额趋势图]:");
        ///1。查询数据库每月售数据  map[monthList,dataList]
        List<Map<String,Object>> cashPerMonth=orderDetailMapper.cashPerMonth(2023);
        //2。计算查询的时间范围
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM");
        LocalDate nowDate = LocalDate.now(); //当前时间：2023-03-22
        LocalDate beforeDate = LocalDate.now().minusYears(1);//去年时间：2022-03-22

        //3，计算出从当前月起，到去年当前月的时间列表//2022-03 ，2022-04，2022-05，......，2023-03
        //List<String> timeList=findDates(beforeDate.toString(),nowDate.toString());
        List<String> timeList=new ArrayList<>();//创建空集合，封装每月表

        List<Integer> dataList = new ArrayList<>();//创建空集合，封装每月销售额
        //log.info("[接口五：月营业额趋势图]:timeList={}",timeList);


        //4，遍历十二个月，查询当前月是否有销售额，如果有将销售额存储到集合中，如果没有，将0存储到集合中
        for (String time : timeList) {
            //询指定月是否存在销售额
            Optional<Map<String,Object>> optional=cashPerMonth.stream()
                    .filter(item->item.get("monthList").equals(time)).findFirst();
            if(optional.isPresent()){
                //存在销售额，将销售额存储到 售额集合中
                BigDecimal dataList1=(BigDecimal)optional.get().get("dataList");
                dataList.add(dataList1.intValue());
            }else{
                ///不存在销售额，将销售额0存储到 售额集合中
                dataList.add(0);
            }
        }
        //5。封装查询结果数据
        Map resultMap = new HashMap();
        resultMap.put("monthList",timeList);  //每月时间列表
        resultMap.put("dataList",dataList); // 每月销售额列表
        return resultMap;
    }


    //参考-----------------------------------------
    public Map cashPer_Bdsafjafvkafkv() {
        ArrayList<String> list = new ArrayList<>();
        ArrayList<BigDecimal> list1 = new ArrayList<>();
        HashMap<Object, Object> map = new HashMap<>();


        BigDecimal bigDecimal = new BigDecimal(0);
        LocalDateTime localDateTime1 = LocalDateTime.now().minusMonths(12);


        while (localDateTime1.isBefore(LocalDateTime.now())) {
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM");
            String localDateStr = localDateTime1.format(fmt);

            LocalDateTime with = localDateTime1.with(TemporalAdjusters.firstDayOfMonth());

            localDateTime1 = localDateTime1.plusMonths(1);

            LocalDateTime with1 = localDateTime1.with(TemporalAdjusters.firstDayOfMonth());

            LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
            qw.between(Orders::getCheckoutTime, with, with1);
            List<Orders> orders = ordersService.list(qw);
            for (Orders order : orders) {
                bigDecimal = bigDecimal.add(order.getAmount());
            }
            list.add(localDateStr);
            list1.add(bigDecimal);
        }
        map.put("monthList", list);
        map.put("dataList", list1);
        return map;
    }

    /**
     * *************看我看我**************
     * 传入两个时间范围，返回这两个时间范围内的所有时间，并保存在一个集合中
     *
     * @param beginTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static List<String> findDates(String beginTime, String endTime) throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endTime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.MONTH, 1);
            allDate.add((sdf.format(calBegin.getTime())).substring(0,(sdf.format(calBegin.getTime())).lastIndexOf("-")));
        }
        System.out.println("时间==" + allDate);
        return allDate;
    }

    //    @GetMapping("/dish")
//    public Map dishCash(Integer cai) {
//        List<dishCategoryCash> dishCategories = new ArrayList<>();
//        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Category::getType, 1);
//        List<Category> list = categoryService.list(wrapper);
//
//        for (Category category : list) {
//            dishCategoryCash dishCategoryCash = new dishCategoryCash();
//            String categoryName = category.getName();
//
//            BigDecimal amount = new BigDecimal(0);
//            int number = 0;
//
//
//            Long categoryId = category.getId();
//
//            LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
//            qw.eq(Dish::getCategoryId, categoryId);
//            List<Dish> dishList = dishService.list(qw);
//
//            for (Dish dish : dishList) {
//                Long dishId = dish.getId();
//                LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
//                lqw.eq(OrderDetail::getDishId, dishId);
//
//                List<OrderDetail> list1 = orderDetailService.list(lqw);
//                for (OrderDetail orderDetail : list1) {
//                    amount = amount.add(orderDetail.getAmount());
//                    number += orderDetail.getNumber();
//                }
//            }
//
//            if (cai == 1) {
//                dishCategoryCash.setValue(amount);
//            } else {
//                dishCategoryCash.setValue(number);
//            }
//            dishCategoryCash.setName(categoryName);
//            dishCategories.add(dishCategoryCash);
//        }
//        Map<String, Object> map = new HashMap<>();
//        map.put("dishCategoryCash", dishCategories);
//        return map;
//    }
//
//    @GetMapping("/cash")
//    public Map dishcash(Integer tao) {
//
//
//        List<dishCategoryCash> dishCategories = new ArrayList<>();
//        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Category::getType, 2);
//
//        List<Category> list = categoryService.list(wrapper);
//
//        for (Category category : list) {
//            dishCategoryCash dishCategoryCash = new dishCategoryCash();
//            String categoryName = category.getName();
//
//            BigDecimal amount = new BigDecimal(0);
//            int number = 0;
//
//
//            Long categoryId = category.getId();
//            LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
//            qw.eq(Setmeal::getCategoryId, categoryId);
//            List<Setmeal> setmealList = setmealService.list(qw);
//
//            for (Setmeal setmeal : setmealList) {
//                Long setmealId = setmeal.getId();
//                LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
//                lqw.eq(OrderDetail::getSetmealId, setmealId);
//                List<OrderDetail> list1 = orderDetailService.list(lqw);
//                for (OrderDetail orderDetail : list1) {
//                    amount = amount.add(orderDetail.getAmount());
//                    number += orderDetail.getNumber();
//                }
//            }
//            dishCategoryCash.setName(categoryName);
//            if (tao == 1) {
//                dishCategoryCash.setValue(amount);
//            } else {
//                dishCategoryCash.setValue(number);
//            }
//            dishCategories.add(dishCategoryCash);
//        }
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("dishCategoryCash", dishCategories);
//        return map;
//    }


    //接口一：菜系营收占比分析  请求url地址：/statics/dishCash
//    @GetMapping("/dishCash")
//    public List<Map> dishCategoryCash(){
//        Map mapValue=new HashMap();
//        AtomicInteger amount = new AtomicInteger(0);//总价
//        List<Map> dishCategoryCash=new ArrayList();
//
//        //T1  --查找所有菜系
//        List<Category> categoryList = categoryService.list(
//                new LambdaQueryWrapper<Category>()
//                        .eq(Category::getType, 1).orderByDesc(Category::getUpdateTime));
//        for (Category category : categoryList) {
//            //map:k-v  [湘菜 id:  金额]
//            mapValue.put(category.getId(),amount);
//            log.info("[>>>菜系营收占比分析]:mapValue={}",mapValue);
//        }
//
//        //--查找订单所有菜系
//        List<OrderDetail> orderDetailList = orderDetailService.list(
//                new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getSetmealId, null));
//        //T2  --查找所有菜系
//        for (OrderDetail item : orderDetailList) {
//
//            Long dishId = item.getDishId();
//            Long categoryId = dishService.getById(dishId).getCategoryId();//从菜品id得到分类id
//
//            BigDecimal multiply = item.getAmount().multiply(new BigDecimal(item.getNumber())); //数量*单价
//            int newValue= new AtomicInteger((int) mapValue.get(categoryId)).addAndGet(multiply.intValue());//累计价钱
//            mapValue.put(categoryId,newValue);//加入对应map
//            log.info("[>>>菜系营收占比分析]:item-mapValue={}",mapValue);
//        }
//
//        for (Category category : categoryList) {
//            log.info("[>>>菜系营收占比分析]:{}={}",mapValue.get(category.getName()),mapValue.get(category.getId()));
//
//            //mapValue.get(category.getId())  当前id非总价
//            Map newMap=new HashMap();
//
//            //{ "value": 1048, "name": "徽菜" },
//            newMap.put("value",mapValue.get(category.getId())); //封装value
//            newMap.put("value",mapValue.get(category.getName())); //封装name
//
//            dishCategoryCash.add(newMap);
//        }
//
//        return dishCategoryCash;
//    }

}
